package com.kd.juhaowan.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.flyjingfish.shapeimageviewlib.ShapeImageView;

import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.kd.juhaowan.R;
import com.kd.juhaowan.http.api.DianZanApi;
import com.kd.juhaowan.http.api.ReciveGiftApi;
import com.kd.juhaowan.http.model.CommentModel;
import com.kd.juhaowan.http.model.FollowResult;
import com.kd.juhaowan.http.model.GameModel;
import com.kd.juhaowan.http.model.GiftModel;
import com.kd.juhaowan.http.model.HttpData;
import com.kd.juhaowan.http.model.HttpListData;
import com.kd.juhaowan.ui.CommentDetailActivity;
import com.kd.juhaowan.ui.GameDetailActivity2;
import com.kd.juhaowan.ui.GameDjqActivity;
import com.kd.juhaowan.ui.GameGiftActivity;
import com.kd.juhaowan.ui.adapter.BaseRecyclerViewAdapter;
import com.kd.juhaowan.ui.adapter.BaseViewHolder;
import com.kd.juhaowan.ui.dialog.ConfirmDialog;
import com.kd.juhaowan.ui.holder.CommentViewHolder;
import com.kd.juhaowan.ui.holder.CommentViewHolderOnePic;
import com.kd.juhaowan.ui.holder.CommentViewHolderThreePic;
import com.kd.juhaowan.ui.holder.CommentViewHolderTwoPic;
import com.kd.juhaowan.ui.holder.GameInfoImageViewHolder;
import com.kd.juhaowan.ui.listener.OnItemClickListener;
import com.kd.juhaowan.ui.listener.OnItemDianzanListener;
import com.kd.juhaowan.utils.DeviceUtil;
import com.kd.juhaowan.utils.GlideHelper;
import com.kd.juhaowan.utils.LogUtil;
import com.luck.picture.lib.entity.LocalMedia;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class GameDetailFragment extends BaseFragment implements OnItemClickListener, OnItemDianzanListener {

    @BindView(R.id.gamedetail_image)
    ShapeImageView videoView;
    @BindView(R.id.gamedetail_icon)
    ShapeImageView iconView;
    @BindView(R.id.gamedetail_name)
    TextView nameView;
    @BindView(R.id.gamedetail_cat)
    TextView cateView;
    @BindView(R.id.gamedetail_people)
    TextView peopleView;

    @BindView(R.id.gamedetail_zhekou_layout)
    LinearLayout zhekouLayout;
    @BindView(R.id.gamedetail_zhekou_text)
    TextView zhekouText;
    @BindView(R.id.gamelist_tag)
    LinearLayout tagListview;
    @BindView(R.id.gamedetail_star)
    TextView starView;
    @BindView(R.id.gamedetail_fuli)
    TextView fuliView;
    @BindView(R.id.item_lingqu)
    TextView sixView;
    @BindView(R.id.gamedetail_gift_count)
    TextView giftCountView;
    @BindView(R.id.gamedetail_djq_count)
    TextView djqCountView;
    @BindView(R.id.gamedetail_all)
    TextView comentAllView;
    @BindView(R.id.gamedetail_imageList)
    RecyclerView imageListView;
    @BindView(R.id.gamedetail_pinglun)
    RecyclerView giftListView;
    private GameModel model;
    private List<CommentModel> commentModels;
    private BaseRecyclerViewAdapter<BaseViewHolder, CommentModel> giftAdapter;
    private LinearLayout.LayoutParams params;
    private BaseRecyclerViewAdapter<GameInfoImageViewHolder, LocalMedia> mAdapter;
    private ArrayList<LocalMedia> mediaList=new ArrayList<>();
    private ArrayList<LocalMedia> VedioList=new ArrayList<>();
    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.fragment_gamedetail;
    }

    @OnClick(R.id.gamedetail_vedio)
    public void onVedioClick(){
        GlideHelper.imagePreview((Activity) getActivity(),0,VedioList);
    }

    @OnClick(R.id.gamedetail_djq_layout)
    public void onDjqClick(){
        Intent in = new Intent(getActivity(), GameDjqActivity.class);
        in.putExtra("game",model);
        startActivity(in);
    }
    @OnClick(R.id.gamedetail_gift_layout)
    public void ongiftClick(){
        Intent in = new Intent(getActivity(), GameGiftActivity.class);
        in.putExtra("game",model);
        startActivity(in);
    }


    private ConfirmDialog dialog = null;
    @OnClick(R.id.item_lingqu)
    public void onLingquClick(){
        GiftModel giftModel= model.getSix_package();
        if(giftModel!=null&&giftModel.getIs_receive()==0){
            EasyHttp.post(this).api(new ReciveGiftApi(giftModel.getId(),model.getId(), DeviceUtil.isInstallApp(getContext(),model.getGame_package_name())?1:2)).request(new HttpCallbackProxy<HttpData<GiftModel>>(this){
                @Override
                public void onHttpSuccess(HttpData<GiftModel> result, boolean cache) {
                    super.onHttpSuccess(result, cache);
                    sixView.setText("已领取");
                    sixView.setBackgroundResource(R.drawable.gift_btn_recived);
                    if(!DeviceUtil.isInstallApp(getContext(),model.getGame_package_name())){

                        ((GameDetailActivity2)getActivity()).onLoginClick(null);
                    }


                    ConfirmDialog.Builder builder = new ConfirmDialog.Builder(getContext());
                    builder.setMessage(result.getMessage());
                    builder.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();

                            if(DeviceUtil.isInstallApp(getContext(),model.getGame_package_name())){
                                final Intent intent = getContext().getPackageManager().getLaunchIntentForPackage(model.getGame_package_name());
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                                startActivity(intent);
                            }
                        }
                    });
                    dialog = builder.create();
                    dialog.show();

                }
            });
        }

    }

    @OnClick(R.id.gamedetail_all)
    public void onAllClick(){
        ((GameDetailActivity2)getActivity()).goToAllComment();
    }
    @Override
    protected void onButterKnifeCreateViewAfter() {
        super.onButterKnifeCreateViewAfter();
        params =new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.rightMargin= UIUtil.dip2px(getContext(),5);
        model = (GameModel) getArguments().getSerializable("model");
        commentModels = ((HttpListData<CommentModel>) getArguments().getSerializable("comment")).getData().getList();
        LogUtil.debugLog("commentModels.oldsize"+commentModels.size());
        if(commentModels!=null&&commentModels.size()>3){
            comentAllView.setVisibility(View.VISIBLE);
            commentModels =commentModels.subList(0,3);
        }else {
            comentAllView.setVisibility(View.GONE);
        }
        LocalMedia media1 = LocalMedia.generateHttpAsLocalMedia(model.getVideofiles());
        VedioList.add(media1);
        if(model.getImages()!=null){
            for (String abc :model.getImages()) {
                LocalMedia media = LocalMedia.generateHttpAsLocalMedia(abc);
                mediaList.add(media);
            }
        }
        LogUtil.debugLog("commentModels.size"+commentModels.size());
        setAdapter();
        setView();
    }

    @Override
    protected void reInitDate() {

    }

    public void setCommentModels(List<CommentModel> list){
        this.commentModels = list;
        if(commentModels!=null&&commentModels.size()>3){
            commentModels =commentModels.subList(0,2);
        }
        giftAdapter.resetAdapterData(list);
    }


    @Override
    public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int position) {
        if(viewHolder instanceof GameInfoImageViewHolder)
        {
            GlideHelper.imagePreview(getActivity(),position,mediaList);

        }else if(viewHolder instanceof CommentViewHolder ||viewHolder instanceof CommentViewHolderOnePic
                ||viewHolder instanceof CommentViewHolderTwoPic
                ||viewHolder instanceof CommentViewHolderThreePic){
            Intent intent = new Intent(getActivity(), CommentDetailActivity.class);
            intent.putExtra("model",giftAdapter.getItem(position));
            startActivity(intent);
        }
    }

    @Override
    public void onItemDianzanClick(BaseViewHolder viewHolder, int position) {
        CommentModel item = giftAdapter.getItem(position);
        EasyHttp.post(this).api(new DianZanApi(model.getId(),item.getId())).request(new HttpCallbackProxy<HttpData<FollowResult>>(this){
            @Override
            public void onHttpSuccess(HttpData<FollowResult> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                if(result.getData().getStatus()==1){
                    item.setLike_count(item.getLike_count()+1);
                    item.setIs_like(1);
                }else {
                    item.setLike_count(item.getLike_count()-1);
                    item.setIs_like(0);
                }
                giftAdapter.notifyItemChanged(position,item);
            }
        });
    }

    private void setAdapter(){
        giftAdapter = new BaseRecyclerViewAdapter<BaseViewHolder, CommentModel>() {
            @NonNull
            @Override
            public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                BaseViewHolder holder;
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                if(viewType==0){
                    View view = inflater.inflate(R.layout.item_comment, null, false);
                    holder=new CommentViewHolder(view);
                }else if (viewType==1){
                    View view = inflater.inflate(R.layout.item_comment_one, null, false);
                    holder=new CommentViewHolderOnePic(view);
                }else if (viewType ==2){
                    View view = inflater.inflate(R.layout.item_comment_two, null, false);
                    holder=new CommentViewHolderTwoPic(view);
                }else {
                    View view = inflater.inflate(R.layout.item_comment_three, null, false);
                    holder=new CommentViewHolderThreePic(view);
                }
                holder.setOnItemClickListener(getOnItemClickListener());
                return  holder;

            }

            @Override
            public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
                if(holder instanceof CommentViewHolder){
                    ((CommentViewHolder)holder).setDate(getItem(position),position,position==commentModels.size()-1);
                }else if (holder instanceof CommentViewHolderOnePic){
                    ((CommentViewHolderOnePic)holder).setDate(getItem(position),position,position==commentModels.size()-1);
                }else if (holder instanceof CommentViewHolderTwoPic){
                    ((CommentViewHolderTwoPic)holder).setDate(getItem(position),position,position==commentModels.size()-1);
                }else if (holder instanceof CommentViewHolderThreePic){
                    ((CommentViewHolderThreePic)holder).setDate(getItem(position),position,position==commentModels.size()-1);
                }

            }

            @Override
            public int getItemViewType(int position) {
                CommentModel model =giftAdapter.getItem(position);
                String[] images = model.getImages();
                if(images==null||images.length==0){
                    return 0;
                }else {
                    return images.length>=3?3:images.length;
                }

            }
        };
        giftAdapter.setOnItemClickListener(this);
        giftAdapter.resetAdapterData(null);
//        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        layoutManager.setOrientation(RecyclerView.VERTICAL);
//        DividerItemDecoration decoration = new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL);
//        decoration.setDrawable(getContext().getDrawable(R.drawable.listview_diver));
//        giftListView.addItemDecoration(decoration);
        giftListView.setLayoutManager(layoutManager);
        giftListView.setAdapter(giftAdapter);


        LinearLayoutManager layoutManager2 = new LinearLayoutManager(getContext());
        layoutManager2.setOrientation(RecyclerView.HORIZONTAL);
        imageListView.setLayoutManager(layoutManager2);

        mAdapter = new BaseRecyclerViewAdapter<GameInfoImageViewHolder, LocalMedia>() {
            @NonNull
            @Override
            public GameInfoImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                View view = inflater.inflate(R.layout.item_gameinfo_image, parent, false);
                GameInfoImageViewHolder holder = new GameInfoImageViewHolder(view);
                holder.setOnItemClickListener(getOnItemClickListener());
                return holder;

            }

            @Override
            public void onBindViewHolder(@NonNull GameInfoImageViewHolder holder, int position) {
                holder.setDate(getItem(position).getAvailablePath());
            }
        };

        mAdapter.setOnItemClickListener(this);
        imageListView.setAdapter(mAdapter);

    }


    private void setView(){
        GlideHelper.loadGoodsCover(Glide.with(iconView),iconView,model.getLogoimage());
        GlideHelper.loadGoodsCover(Glide.with(videoView),videoView,model.getVideofiles());
        nameView.setText(model.getName());
        starView.setText(model.getScore());
        cateView.setText(model.getCat_name());
        peopleView.setText(model.getPeople_are_playing()+"人在玩");
        fuliView.setText(Html.fromHtml(model.getGame_benefits()));
        giftCountView.setText(model.getNumber_regular()+"");
        djqCountView.setText(model.getNumber_voucher()+"");
        GiftModel giftModel= model.getSix_package();
        if(giftModel==null){
            sixView.setText("不可领");
            sixView.setBackgroundResource(R.drawable.gift_btn_recived);
        }else if (giftModel.getIs_receive()==1){
            sixView.setText("已领取");
            sixView.setBackgroundResource(R.drawable.gift_btn_recived);
        }else {
            sixView.setText("领取");
            sixView.setBackgroundResource(R.drawable.login_small_btn);
        }
        if(model.getDiscount()>0){
            zhekouLayout.setVisibility(View.VISIBLE);
            zhekouText.setText(model.getDiscount()+"折直充");
        }else{
            zhekouLayout.setVisibility(View.GONE);
        }

        String[] tags =model.getTags();
        LogUtil.debugLog("dafa"+tags==null?"null":tags.length+"");
        if(tags!=null&&tags.length>0){
            tagListview.setVisibility(View.VISIBLE);
            tagListview.removeAllViews();
            for (String adb:tags) {
                TextView tv=new TextView(getContext());
                tv.setGravity(Gravity.CENTER);
                tv.setBackgroundResource(R.drawable.tag_bg);
                tv.setPadding(UIUtil.dip2px(getContext(),5),0,UIUtil.dip2px(getContext(),5),0);
                tv.setText(adb);
                tv.setTextColor(getContext().getColor(R.color.login_edit_hint));
                tv.setTextSize(11);
                tagListview.addView(tv,params);
            }


//            searchHistoryAdapter.resetAdapterData(Arrays.asList(tags));
        }else {
            tagListview.setVisibility(View.GONE);
        }
//        List<CommentModel> temp = new ArrayList<>();
//        temp.addAll(commentModels);
//        temp.addAll(commentModels);
//        temp.addAll(commentModels);
//        temp.addAll(commentModels);
        giftAdapter.resetAdapterData(commentModels);
        mAdapter.resetAdapterData(mediaList);
//        if(commentModels!=null&&commentModels.size()>3){
//            comentAllView.setVisibility(View.VISIBLE);
//        }else {
//            comentAllView.setVisibility(View.GONE);
//        }
    }
}
